package router

import (
	"net/http"
	"sems/controller"
	middleware "sems/middlewares"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func SetupRouter(mode string) *gin.Engine {
	if mode == gin.ReleaseMode {
		gin.SetMode(gin.ReleaseMode) // gin设置成发布模式
	}
	r := gin.Default()
	r.NoRoute(func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"msg": "404",
		})
	})
	// 配置 CORS 中间件
	r.Use(cors.New(cors.Config{
		AllowAllOrigins:  true, // 允许所有来源
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))
	RegisterRoutes(r)
	return r
}

func RegisterRoutes(r *gin.Engine) {
	apiGroup := r.Group("/api/v1")
	apiGroup.GET("/ping", func(context *gin.Context) { // 测试方法，测试是否生效
		context.String(http.StatusOK, "pong")
	})
	apiGroup.POST("/register", controller.Register)
	apiGroup.POST("/login", controller.Login)
	apiGroup.Use(middleware.AuthMiddleware()) // 应用JWT认证中间件，可判断用户token中的账号密码；
	{
		// 在这里添加模块的路由
		apiGroup.GET("/getEquipments", controller.GetEquipments)
		apiGroup.GET("/getEquipmentInfo", controller.GetEquipmentInfo)
		apiGroup.PUT("/bookEquipments", controller.BookEquipments)
		apiGroup.PUT("/borrowEquipments", controller.BorrowEquipments)
		apiGroup.GET("/getBorrowRecord", controller.GetBorrowRecord)
		////管理
		apiGroup.GET("/getUsers", controller.GetUsers)
		apiGroup.GET("/getUserInfo", controller.GetUserInfo)
		apiGroup.PUT("/editUserRole", controller.EditUserRole)
		apiGroup.POST("/uploadPicture", controller.UploadPicture)
		apiGroup.PUT("/editUsers", controller.EditUsers)
		apiGroup.PUT("/editUserPassword", controller.EditUserPassword)
		apiGroup.PUT("/deleteUser", controller.DeleteUser)
		apiGroup.PUT("/deleteEquipment", controller.DeleteEquipment)
		apiGroup.GET("/getEquipmentCategoryName", controller.GetEquipmentCategoryName)
		apiGroup.POST("/addEquipment", controller.AddEquipment)
		////借阅管理
		apiGroup.GET("/getAllBorrowRecord", controller.GetAllBorrowRecord)
	}
}
